package com.qinghuan.threads.chapterTwo;

import sun.misc.Unsafe;

/**
 * @Author: dubao
 * @Date: 2022/5/21 09:38
 * @Description:
 */

/**
 * 疑问：这里static final常量为什么不设置初值就会报错
 */
public class Test2_9_2 {


}

class TestUnSafe {
    //获取Unsafe的实例（2.2.1）
    static final Unsafe unsafe = Unsafe.getUnsafe();
    //记录变量state在类TestUnsafe中的偏移量(2.2.2)
    static long stateOffset;
    //变量(2.2.3)
    private volatile long state = 0L;
    static {
        try {
            //获取state变量在类TestSafe中的偏移量（2.2.4）
            stateOffset = unsafe.objectFieldOffset(TestUnSafe.class.getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //创建实例，并且设置state值为（2.2.5）
        TestUnSafe test = new TestUnSafe();
        boolean success = unsafe.compareAndSwapInt(test, stateOffset, 0, 1);
        System.out.println(success);
    }

}
